package com.sgb.kjwl.view.ui.fragment.pick;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentDemandSearchListBinding;
import com.sgb.kjwl.di.pick.DaggerPickFragComponent;
import com.sgb.kjwl.di.pick.PickFragModule;
import com.sgb.kjwl.model.entity.pick.DemandSearchBean;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickSearchActivity;
import com.sgb.kjwl.viewmodel.pick.DemandlistModle;
import com.sgb.zhaocai.entity.ProjectListEntity;
import com.sgb.zhaocai.view.demand.adapter.ProjectAdapter;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.xrecyclerview.XRecyclerView;
import java.util.List;
import javax.inject.Inject;

/**
 * 招采-搜索-需求预告
 */
public class DemandSearchListFragment extends AppFragment implements MemberStatusView.OnChooseListener{
    private DemandSearchBean requestBean = new DemandSearchBean();
    public static final String KEY_TYPE = "type";
    //搜索内容
    private String searchName ="";
    private PickSearchActivity pickSearchActivity;
    private int total;
    private FragmentDemandSearchListBinding mBinding;
    @Inject
    DemandlistModle mModel;
    //地区
    private ThreeLevelAreaWindow mAddressPop;
    //省
    private String province = "";
    //市
    private String city = "";
    //地址
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    //综合排序
    private String sort ="";
    //工程类型
    private String projectType="";
    //项目创建时间
    private String time="";
    private boolean isLoadMore = false;
    private ProjectAdapter projectadapter;

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPickFragComponent.builder()
                .appComponent(appComponent)
                .pickFragModule(new PickFragModule(this))
                .build()
                .inject(this);
    }

    public static DemandSearchListFragment newInstance(String type) {
        DemandSearchListFragment fragment = new DemandSearchListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_demand_search_list, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        searchName = (String) getArguments().get(KEY_TYPE);
        requestBean.setKeyword(searchName);
        pickSearchActivity = (PickSearchActivity) getActivity();
        initView();
        initDataList();
    }

    //初始化view
    private void initView() {
        pickSearchActivity.showTopBack(false);
        //初始化popview
        initializePopView();
        if (projectadapter == null) {
            projectadapter = new ProjectAdapter(getActivity(), null);
        }
        projectadapter.setOnItemClick(new AdapterOnItemClick<ProjectListEntity>() {
            @Override
            public void onItemClick(ProjectListEntity entity, int position) {
                mModel.getH5Data(entity.getId());
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mBinding.recyclerView.setLayoutManager(layoutManager);
        mBinding.recyclerView.setHasFixedSize(true);
        //解决数据加载完成后, 没有停留在顶部的问题
        mBinding.recyclerView.setFocusable(false);
        mBinding.recyclerView.setAdapter(projectadapter);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initDataList();
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                requestBean.page++;
                //上拉加载更多
                mModel.ProjectList(requestBean);
            }
        });
    }
    /**
     * 初始化popview
     */
    private void initializePopView() {
        //地区
        initAddressPopup();
        //综合排序
        mBinding.sort.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        //工程类型
        mBinding.projectType.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        //创建时间
        mBinding.creationTime.initPopup(mBinding.grayLayout, mBinding.popLine, this);
    }

    //地区
    private void initAddressPopup() {
        mBinding.district.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null || scrData.size() == 0) {
                    mModel.getAddressModel();
                    return;
                }
                mBinding.popLine.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                    mBinding.district.updateChooseTextStatus(-2, null);
                } else {
                    mBinding.district.updateChooseTextStatus(-1, mBinding.district.getKeyName());
                }
                mAddressPop.showPopwindow0(mBinding.popLine);
            }
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                province = "";
                city = "";
                requestBean.setProvince(province);
                requestBean.setCity(city);
                mBinding.district.updateChooseTextStatus(0, mBinding.district.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    province = entity.getProvinceNo();
                    requestBean.setProvince(province);
                    mBinding.district.updateChooseTextStatus(1, entity.getProvinceName());
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        city = entity.getCityNo();
                        requestBean.setCity(city);
                        mBinding.district.updateChooseTextStatus(1, entity.getCityName());
                    }
                }
                //刷新数据
                initDataList();
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                mBinding.district.updateChooseTextStatus(1, null);
            } else {
                mBinding.district.updateChooseTextStatus(0, mBinding.district.getKeyName());
            }
        });
    }

    //请求列表数据信息
    private void initDataList() {
        if (requestBean == null) {
            requestBean = new DemandSearchBean();
        }
        isLoadMore = false;
        requestBean.page = 1;
        mModel.ProjectList(requestBean);
    }

    public void setProjectList(List<ProjectListEntity> data, boolean isLastPage) {
        RecyclerRefreshing();
        if (isLoadMore) {
            if (data != null && data.size() > 0) {
                projectadapter.addDatas(data);
            }
            mBinding.recyclerView.setNoMore(isLastPage);
        } else {
            if (data != null && data.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mBinding.recyclerView.setVisibility(View.VISIBLE);
                projectadapter.setDatas(data);
                mBinding.recyclerView.scrollToPosition(0);
                mBinding.recyclerView.setNoMore(isLastPage);
            } else {
                projectadapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
                mBinding.recyclerView.setVisibility(View.GONE);
            }
        }
    }
    private void RecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    /**
     * 地址
     * @param data
     */
    public void setAddressList(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            String ProvinceCode = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE, "");
            if (!TextUtils.isEmpty(ProvinceCode)){
                mAddressPop.setData(data, true,ProvinceCode );
            }else {
                mAddressPop.setData(data, true );
            }
            mBinding.popLine.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(province) || !TextUtils.isEmpty(city)) {
                mBinding.district.updateChooseTextStatus(-2, null);
            } else {
                mBinding.district.updateChooseTextStatus(-1, mBinding.district.getKeyName());
            }
            mAddressPop.showPopwindow0(mBinding.popLine);
        }
    }

    //pop初始化数据
    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "综合排序":
                mModel.getSortType();
                break;
            case "工程类型":
                mModel.getProjectTypeList();
                break;
            case "创建时间":
                mModel.getTime();
                break;
        }
    }
    //pop点击事件
    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        String name = position == 0 ? "" : entity.getTypeName();
        switch (mKeyName) {
            case "综合排序":
                if (!TextUtils.equals(no, sort)) {
                    sort = no;
                    requestBean.setSortMethod(sort);
                }
                break;
            case "工程类型":
                if (!TextUtils.equals(name, projectType)) {
                    projectType = name;
                    requestBean.setEngineeringType(projectType);
                }
                break;
            case "创建时间":
                if (!TextUtils.equals(no, time)) {
                    time = no;
                    requestBean.setPlanUseTime(time);
                }
                break;
        }
        initDataList();
    }

    /**
     * 综合排序
     * @param datas
     */
    public void setSortTypeList(List<CommonPopEntity> datas) {
        setChooseItemData(1,datas);
    }

    /**
     * 工程类型
     * @param data
     */
    public void setProjectTypeList(List<CommonPopEntity> data) {
        setChooseItemData(2,data);
    }

    /**
     * 时间
     * @param data
     */
    public void setTime(List<CommonPopEntity> data) {
        setChooseItemData(3,data);
    }

    //弹窗信息
    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        switch (type) {
            case 1://排序方式
                mBinding.sort.setData(data, sort);
                break;
            case 2://工程类别
                mBinding.projectType.setData(data, projectType);
                break;
            case 3://创建时间
                mBinding.creationTime.setData(data, time);
                break;

        }
    }
    //跳转到详情界面
    public void showUrl(String url) {
        WebViewX5HostActivity.start(getActivity(), url);
    }

    public void fullScroll(){
        mBinding.recyclerView.getLayoutManager().scrollToPosition(0);
    }
}
